package com.yuanzheng.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 权限---设置
 *
 * @author yuanzheng
 * @date 2020/4/15-13:17
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        // 创建ShiroFilterFactoryBean,并管理defaultWebSecurityManager对象---3
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 添加安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        /*
         * anon 无需认证
         * authc 必须认证
         * user 必须有 记住我 功能才能访问
         * perms 拥有某个资源的权限才能访问
         * role 拥有某个角色权限才能访问
         * */
        // 添加权限规则
        Map<String, String> filterMap = new LinkedHashMap<>();

        // 设置授权
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "perms[user:update]");

        // 设置路径权限
        //filterMap.put("/user/add","anon");
        //filterMap.put("/user/update","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //设置登录请求
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/toUnauPage");

        return shiroFilterFactoryBean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        // 创建DefaultWebSecurityManager对象，并管理realm对象---2
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean(name = "userRealm")
    public UserRealm getUserRealm() {
        // 创建realm对象，需要自定义---1
        return new UserRealm();
    }

    @Bean
    public ShiroDialect getShiroDialect() {
        // 整合ShiroDialect ---4
        return new ShiroDialect();
    }

}
